package b_workqueue;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
import org.junit.Test;
import utils.RabbitMQUtils;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 雷哥
 * @Date: 2020/10/06/22:54
 * @Description: 消费者1
 */
public class Consumer1 {

  private int i=0;

  @Test
  public void receiveMessage() throws  Exception{



    Connection connection = RabbitMQUtils.getConnection();
    //创建信道
    Channel channel = connection.createChannel();
    //声明队列
    channel.queueDeclare("hello",false,false,false,null);
    //设置一次只接收一条未确认的消息
    channel.basicQos(2);
    //接收消息 参数2:关闭自动确认消息
    channel.basicConsume("hello",false,new DefaultConsumer(channel){
      @Override
      public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties,
          byte[] body) throws IOException {
//        try {
//          Thread.sleep(500);
//        } catch (InterruptedException e) {
//          e.printStackTrace();
//        }
//        i++;
//        if(i<=2){
//          int a=10/0;
//        }
        System.out.println("消息者【1】接收到消息："+new String(body));
        //手动签收消息
        channel.basicAck(envelope.getDeliveryTag(),false);
      }
    });
    System.in.read();
    RabbitMQUtils.closeChannelAndConnection(channel,connection);
  }

}
